﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Rainbow.common.comparer
{
    public class NaturalStringComparer : IComparer<string>
    {
        private static readonly Regex _splitter = new Regex(@"(\d+|\D+)", RegexOptions.Compiled);

        public int Compare(string x, string y)
        {
            string[] xParts = _splitter.Split(x);
            string[] yParts = _splitter.Split(y);

            int i = 0;
            while (i < xParts.Length && i < yParts.Length)
            {
                if (int.TryParse(xParts[i], out int xValue) && int.TryParse(yParts[i], out int yValue))
                {
                    if (xValue != yValue)
                    {
                        return xValue.CompareTo(yValue);
                    }
                }
                else
                {
                    int result = string.Compare(xParts[i], yParts[i], StringComparison.Ordinal);
                    if (result != 0)
                    {
                        return result;
                    }
                }
                i++;
            }

            return xParts.Length - yParts.Length;
        }
    }
}
